package com.controller;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.entity.Article;
import com.entity.Comment;
import com.entity.User;
import com.service.ArticleService;
import com.service.CommentService;
import com.service.UserService;

/**
 * 管理员控制层
 * @author MingCha Yang
 */
@Controller@RequestMapping("/admin")
public class AdminController {
	@Resource(name = "userServiceImpl")
	private UserService userService;
	@Resource(name = "articleServiceImpl")
	private ArticleService articleService;
	@Resource(name = "commentServiceImpl")
	private CommentService commentService;
	@RequestMapping("/login")
	public String login(String userName,String userPass,ModelMap m,HttpSession session){
		User login = userService.login(userName, userPass);
		if(null != login) {
			m.put("msg", "登录成功了");
			List<Article> listRecentArticle = articleService.listRecentArticle(6);
			List<Comment> listRecentComment = commentService.listRecentComment(5);
			m.put("listRecentArticle", listRecentArticle);
			m.put("listRecentComment", listRecentComment);
			session.setAttribute("user_session", login);
			return "index";
		}else {
			m.put("msg", "您的用户名或密码错误了");
			return "login";
		}
		
	}
	@RequestMapping(value = "/add",method = RequestMethod.GET)
	public String gotoadduserPage() {
		
		return "User/user-add";
		
	}
	@RequestMapping(value = "/add",method = RequestMethod.POST)
	public String addUser(User user,MultipartFile photo,HttpServletRequest req) throws IOException {
		user.setUserLastLoginIp(req.getRemoteAddr());
		user.setUserRegisterTime(new Date());
		user.setUserLastLoginTime(new Date());
		user.setUserStatus(1);
		 user.setUserPhoto(photo.getBytes());
		 userService.addUser(user);
		 return "forward:/admin/userlist";
	}
	@RequestMapping("/userlist")
	public String gotoListPage(ModelMap m) {
		List<User> users= userService.getUserList();
		m.put("users", users);
		return "User/user-list";
	}
	@RequestMapping("/photo/{userId}")
	public void showPhoto(@PathVariable("userId") Integer userId,HttpServletResponse response) throws IOException {
		
		User u = userService.getUserById(userId);
		response.setContentType("image/jpg");
		ServletOutputStream sos = response.getOutputStream();//网络字节流
		sos.write(u.getUserPhoto());
		sos.flush();
		
		
	}

}
